<?php
namespace my;
class BaiduAi {
    const API_KEY = "";
    const SECRET_KEY = "";

    public function run() {
        $access_token = $this->getAccessToken();
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token={$access_token}",
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_CUSTOMREQUEST => 'POST',
//            CURLOPT_POSTFIELDS =>'{"messages": [ {"role": "user","content": "你是谁"}],"disable_search":false,"enable_citation":false}',
            CURLOPT_POSTFIELDS =>'{"messages":[{"role":"user","content":"你会php代码吗"},{"role":"assistant","content":"是的，我可以理解和生成PHP代码。PHP是一种流行的服务器端脚本语言，广泛用于Web开发。以下是一个简单的PHP代码示例，用于输出“Hello, World!”：\\n\\n\\n```php\\n<?php\\necho \\"Hello, World!\\";\\n?>\\n```\\n当然，我可以帮助你编写更复杂的PHP代码，解决特定的问题或实现特定的功能。如果你有任何PHP编程的需求或问题，请随时告诉我，我会尽力提供帮助。"},{"role": "user","content": "我刚才问你什么了"}],"disable_search":false,"enable_citation":false}',

            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),

        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }

    /**
     * 使用 AK，SK 生成鉴权签名（Access Token）
     * @return string 鉴权签名信息（Access Token）
     */
    public function getAccessToken(){
        $curl = curl_init();
        $postData = array(
            'grant_type' => 'client_credentials',
            'client_id' => self::API_KEY,
            'client_secret' => self::SECRET_KEY
        );
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $rtn = json_decode($response);
        return $rtn->access_token;
    }
}